/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.bincent.common.web.handler;

import com.bincent.common.exception.AuthException;
import com.bincent.common.exception.BizException;
import com.bincent.common.web.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 * description
 *
 * @author Matrix
 * @date 2020-08-25 16:19
 * @since 1.0.2
 */
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
	private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	@ExceptionHandler(value = AuthException.class)
	@ResponseBody
	public ResponseEntity<Result<String>> handleAuthExcpetion(AuthException authException) {
		log.error("auth exception", authException);
		Result<String> result = new Result<>();
		result.setCode(authException.getCode());
		result.setMessage(authException.getMessage());
		return new ResponseEntity<>(result,
				HttpStatus.UNAUTHORIZED);
	}

	@ExceptionHandler(value = BizException.class)
	@ResponseBody
	public ResponseEntity<Result<String>> handleBizException(BizException bizException) {
		log.error("bizException exception", bizException);
		Result<String> result = new Result<>();
		result.setCode(bizException.getCode());
		result.setMessage(bizException.getMessage());
		return new ResponseEntity<>(result,
				HttpStatus.INTERNAL_SERVER_ERROR);
	}

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public ResponseEntity<Result<String>> handleUnExpectedExcpetion(Exception exception) {
		log.error("unexpected exception", exception);
		Result<String> result = new Result<>();
		result.setCode(500);
		result.setMessage("unexpected exception");
		return new ResponseEntity<>(result,
				HttpStatus.INTERNAL_SERVER_ERROR);
	}
}
